package com.hebeu.xwl.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.hebeu.xwl.pojo.*;
import com.hebeu.xwl.service.impl.UserServiceImpl;
import com.hebeu.xwl.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.hebeu.xwl.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hebeu.xwl.utils.RedisConstants.LOGIN_CODE_TTL;

@RestController
@RequestMapping("/common")
@SaCheckLogin
@SaCheckRole("user")
public class UserController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserServiceImpl userService;
    //登录验证码 - 无需校验
    @GetMapping("/captcha")
    @SaIgnore
    public Result captcha(HttpServletRequest request){
        String ip = request.getRemoteAddr();
        System.out.println(ip);
        ValidateCodeUtil.Validate v = ValidateCodeUtil.getRandomCode();
        String value = v.getValue();//获取图片中的验证码值
        //System.out.println(value);
        //直接调用静态方法，返回验证码对象
        System.out.println(value);
        if(v!=null){
            stringRedisTemplate.opsForValue().set(ip,value,60, TimeUnit.SECONDS);
            return new Result(0,v.getImage(),"验证码发送成功");
        }else {
            return new Result(1, null, "验证码发送失败");
        }
    }
    //登录 - 无需校验
    @PostMapping("/userLogin")
    @SaIgnore
    public Result login(HttpServletRequest request, UserloginBean loginBean){
        String userAccount = loginBean.getName();
        String userPassword = loginBean.getPassword();
        String code = loginBean.getVerify().toLowerCase();
        if(code==null||userAccount==null||userPassword==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        //System.out.println(code);
        String ip = request.getRemoteAddr();
        String codes = stringRedisTemplate.opsForValue().get(ip);//验证码
        System.out.println(codes);
        System.out.println(userAccount);
        if(!code.equals(codes)){
            return new Result(1,"验证码错误");
        }
        String salt = userService.findSalt(userAccount);
        if(salt!=null){
            String truePassword = userService.findPassword(userAccount);
            System.out.println(truePassword + "我的密码" + userPassword);
            if(MD5Utils.getSaltverifyMD5(userPassword, salt,truePassword)){
                User user = userService.findUser(userAccount);
                //判断是user
                StpUtil.login(user.getUserId() + "%" + "user");
                return new Result(0,null,"登录成功");
            }
        }
        return new Result(1, null, "登录失败");
    }
    //注册发验证码
    @PostMapping("/userRegister")
    @SaIgnore
    public Result userRegister(HttpServletRequest request,@RequestParam String email){
        if(email==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        Boolean checkEmail = EmailUtil.checkEmail(email);
        if(checkEmail){
                String code = CodeUtil.generateVerifyCode(6);
                MailUtil.sendMail(email, code, "验证码");
                stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+email, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
                //System.out.println(redisTemplate.opsForValue().get(emailIp));
                return new Result(0,"验证码已发送");
            } else {
                return new Result(1,"邮箱已注册");
            }
    }
    //注册
    @PostMapping("/Register")
    @SaIgnore
    public Result Register(HttpServletRequest request,@RequestParam String userEmail,String password,String code){
        if(userEmail==null||password==null||code==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        if(!EmailUtil.checkEmail(userEmail)){
            return new Result(1,"邮箱格式错误");
        }
        User user1 = userService.findUser(userEmail);
        if(user1==null) {
            String codeTrue = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + userEmail);
            if (code.equals(codeTrue)) {
                String salt = MD5Utils.getSalt();//生成一个盐
                password = MD5Utils.getSaltMD5(password, salt);
                // System.out.println(password);
                User user = new User();
                user.setAccount(userEmail);
                user.setPassword(password);
                if (userService.insertUser(user, salt)) {
                    stringRedisTemplate.delete(LOGIN_CODE_KEY + userEmail);
                    return new Result(0, new email(userEmail), "success");
                } else {
                    return new Result(1, "遇到异常，添加失败");
                }
            } else {
                return new Result(1, "验证码错误");
            }
        } else{
          return new Result(1,"邮箱已注册");
        }
    }
    //忘记密码发验证码
    @PostMapping("/forgetPwd")
    @SaIgnore
    public Result forgetPwd(HttpServletRequest request,@RequestParam String email){
        if(email==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        if(!EmailUtil.checkEmail(email)){
            return new Result(1,"邮箱格式错误");
        }
        User user = userService.findUser(email);
        if(user==null){
            return new Result(1,"邮箱未注册");
        }
        String code = CodeUtil.generateVerifyCode(6);
        MailUtil.sendMail(email, code, "验证码");
        String emailIp = email + request.getRemoteAddr();
        stringRedisTemplate.opsForValue().set(emailIp, code, 300, TimeUnit.SECONDS);
        return new Result(0,"邮箱已进行忘记密码操作，请及时前往邮箱修改");
    }
    //忘记密码
    @PostMapping("FchangePwd")
    @SaIgnore
    public Result FchangePwd(HttpServletRequest request,@RequestParam String userEmail,@RequestParam String password,@RequestParam String code){
        if(userEmail==null||password==null||code==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        String emailIp = userEmail + request.getRemoteAddr();
        String codeTrue = stringRedisTemplate.opsForValue().get(emailIp);
        if(userService.findUser(userEmail)==null){
            return new Result(1,"邮箱未注册");
        }
        if(!code.equals(codeTrue)){
            return new Result(1,"验证码错误");
        }
        String saltMD5 = MD5Utils.getSaltMD5(password, userService.findSalt(userEmail));
        userService.UpdatePassword(userEmail,saltMD5);
        return new Result(0,new email(userEmail),"success");
    }
    //修改密码
    @PostMapping("/changePwd")
    public Result changePwd(HttpServletRequest request,@RequestParam String pwd,@RequestParam String newPwd){
        if(pwd==null||newPwd==null){
            return new Result(1,"请检查是否有未填写信息");
        }
        String userid = ((String)StpUtil.getLoginId()).split("%")[0];
        User user = userService.getUserById(Integer.parseInt(userid));
        String account = user.getAccount();
        String salt = userService.findSalt(account);
        if(salt!=null) {
            String truePassword = userService.findPassword(account);
            if (MD5Utils.getSaltverifyMD5(pwd, salt, truePassword)) {
                 newPwd = MD5Utils.getSaltMD5(newPwd, salt);
                userService.UpdatePassword(account,newPwd);
                return new Result(0,new email(account),"Success");
            }else{
                return  new Result(404,"密码验证错误");
            }
        }
        return new Result(1,"账号未注册");
    }
    //登出
    @PostMapping("/userLogout")
    public Result userLogout(){
        StpUtil.logout();
        return new Result(0,"Success");
    }
    //获取用户信息
    @GetMapping("/getUser")
    public Result getUser(){
        int userId = Integer.parseInt(((String)StpUtil.getLoginId()).split("%")[0]);
        User user = userService.getUserById(userId);
        user.setPassword(null);
        return new Result(0, user, "");
    }
}
